<template>
  <div class="book-body" @click="clickEnvent">
    <div v-html="content" :class="['article',{'is-next': isNextChapter}]"></div>
    <div class="book-body-progress" > {{progress}} / {{totalPage}}</div>
  </div>
</template>

<script>
import { getBookChapterContent } from '@/api/book.js'

export default {
  name: 'BookBody',
  props:{
    id: Number,
    bookId: Number
  },
  data () {
    return {
      content: '',
      index: 0,
      width: 0,
      middleX: 0,
      widthGap: 0,
      totalPage: 0,
      clickFlag: false, // 防抖
      article: Object,
      isNextChapter: false
    }
  },
  mounted() {
    this.index = 0
    this.width = document.getElementsByClassName('book-body')[0].offsetWidth
    this.middleX = this.width / 2
  },
  computed: {
    progress() {
      return this.index + 1
    }
  },
  watch: {
    id(newId, oldId){
      getBookChapterContent(this.bookId, newId).then( (response) => {
        if ( response.status != 200) {
          alert(response.statusText)
          return
        }
        this.content = response.data.content
        this.$nextTick( () => {
          this.article = document.querySelector('.article')
          this.totalPage = this.article.scrollWidth / this.width
          this.index = 0
          this.setArticleX()
          setTimeout(() => {
            this.isNextChapter=false
          }, 500)
          
        })
      })
    },
  },
  methods: {
    clickEnvent(e) {
      if (this.clickFlag) {
        return 
      }
      this.clickFlag = true
      if (e.clientX < this.middleX) {
        this.pre()
      } else {
        this.next()
      }
      setTimeout( () => {
        this.clickFlag = false
      }, 1000)
    },
    next() {
      if (this.index >= this.totalPage - 1) {
        this.isNextChapter = true
        console.log("is next chapter", this.isNextChapter)
        this.$emit("next-chapter")
        return
      } else {
        this.index ++ 
        this.setArticleX()    
      }
    },
    pre(){
      if (this.index - 1 < 0) {
        // 需要告诉父组件，返回上一章
        this.$emit("pre-chapter")
        return
      } else {
        this.index -- 
        this.setArticleX()
      }
    },
    setArticleX() {
      this.article.style.transform = `translateX(-${(this.width) * this.index}px)`
    }
  }
}
</script>

<style>
.book-body {
  margin: 0% 10px;
  overflow: hidden;
  height: 92vh;
}
.book-body p {
  margin: 0%;
}

.article{
  columns: calc(100vw) 1;
  column-gap: 0px;
  height: 98%;
  transition: .4s;
}

.article.is-next{
  transition: none;
}

.book-body-progress{
  font-size: xx-small;
  text-align: right;
}
</style>